package com.lmc.health;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lmc.R;
import com.lmc.adapter.HealthListAdapter;
import com.lmc.entity.Faq;
import com.lmc.entity.Health;
import com.lmc.entity.HealthLat;
import com.lmc.entity.HeartType;
import com.lmc.entity.Members;
import com.lmc.health.rate.HeartRateActivity;
import com.lmc.util.HealthTypeUtil;
import com.lmc.util.JsonManager;
import com.lmc.view.DragView;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.FamilyMemberBean;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 健康报告
 */
public class HealthFragment extends Fragment implements TabLayout.OnTabSelectedListener, View.OnClickListener, DragView.OnChanageListener, AdapterView.OnItemClickListener {
    TextView edit_tv;
    TextView member_tv;
    TabLayout health_member_tab;
    ImageView iv_show_members;
    DragView listView;
    HealthListAdapter adapter;
    List<Health.DataBean.ResultBean> list = new ArrayList<>();
    private ArrayList<FamilyMemberBean.MemberBean> members_list = new ArrayList<>();//家庭成员列表
    private Health health;//每日报告的数据

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.lmc_fragment_health, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        edit_tv = (TextView) getView().findViewById(R.id.edit_tv);
        member_tv = (TextView) getView().findViewById(R.id.member_tv);
        health_member_tab = (TabLayout) getView().findViewById(R.id.health_member_tab);
        iv_show_members = (ImageView) getView().findViewById(R.id.iv_show_members);
        listView = (DragView) getView().findViewById(R.id.listView);

        adapter = new HealthListAdapter(list, getContext());
        listView.setAdapter(adapter);

        health_member_tab.addOnTabSelectedListener(this);
        iv_show_members.setOnClickListener(this);
        listView.setOnChangeListener(this);
        edit_tv.setOnClickListener(this);
        listView.setOnItemClickListener(this);
//        getMembers();
        EventBus.getDefault().register(this);

    }

    /**
     * 根据成员id来查询该成员的信息数据
     *
     * @param dataBean
     */
    private void Get(final FamilyMemberBean.MemberBean dataBean) {
        JSONObject params = new JSONObject();
        params.put("device_id", dataBean.getDevice_id());
        params.put("username", dataBean.getUsername());
        Log.e("-------", "device_id:" + dataBean.getDevice_id());
        Log.e("-------", "username:" + dataBean.getUsername());


        HttpRequest.getService().getDaily(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("-----", string);
                    health = JsonManager.parseJson(string, Health.class);

                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });


        HttpRequest.getService().getLatList(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("-----", string);
                    HealthLat healthLat = JsonManager.parseJson(string, HealthLat.class);

                    list.clear();
                    Health.DataBean.ResultBean h = new Health.DataBean.ResultBean();
                    h.setId(R.drawable.lmc_baogao);
                    h.setName("每日健康报告");
                    list.add(h);
                    for (HealthLat.DataBean bean : healthLat.getData()) {
                        if (bean.getValue() != null) {
                            Health.DataBean.ResultBean value = new Health.DataBean.ResultBean();
                            value.setName(HealthTypeUtil.getName(bean.getName()));
                            value.setTname(bean.getName());
                            value.setValue(bean.getValue().getValue());
                            value.setUnit(HealthTypeUtil.getUnit(bean.getName()));
                            value.setDate(bean.getValue().getDate());
                            value.setApplogo(bean.getValue().getApplogo());
                            value.setUsername(bean.getValue().getUsername());
                            value.setAge(bean.getValue().getAge());
                            value.setCensusid(bean.getValue().getCensusid());
                            value.setCity(bean.getValue().getCity());

                            value.setDevice_id(bean.getValue().getDevice_id());
                            value.setDiseasestate(bean.getValue().getDiseasestate());
                            value.setDiseasestateid(bean.getValue().getDiseasestateid());
                            value.setGender(bean.getValue().getGender());
                            value.setId(HealthTypeUtil.getLogo(bean.getName()));
                            list.add(value);
                        } else {
                            Health.DataBean.ResultBean value = new Health.DataBean.ResultBean();
                            value.setName(HealthTypeUtil.getName(bean.getName()));
                            value.setTname(bean.getName());
                            value.setValue("");
                            value.setUnit("--");
                            value.setDate(0);
                            value.setApplogo("");
                            value.setUsername(dataBean.getUsername());
                            value.setAge(0);
                            value.setCensusid("");
                            value.setCity("");

                            value.setDevice_id(dataBean.getDevice_id());
                            value.setDiseasestate("");
                            value.setDiseasestateid(0);
                            value.setGender("");
                            value.setId(HealthTypeUtil.getLogo(bean.getName()));
                            list.add(value);
                        }

                    }
                    adapter.notifyDataSetChanged();

                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    /**
     * 查询家庭成员
     */

    private void getMembers() {
        //查询家庭成员时，获取device_id是在个人中心异步的，所以这里延迟1秒请求
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                JSONObject params = new JSONObject();
                params.put("device_id", SharePreferenceUtil.getDeviceId(getContext()));
                params.put("username", SharePreferenceUtil.getUserName(getContext()));

                HttpRequest.getService().getFamilyMember(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String json = response.body().string();
                            Log.e("-----------", "获取家庭成员列表：" + json);
                            members_list.clear();
                            JSONObject jsonObject = JSONObject.parseObject(json);
                            if (jsonObject != null) {
                                JSONArray dataArray = jsonObject.getJSONArray("data");
                                if (dataArray != null) {
                                    if (dataArray.size() > 0) {
                                        JSONObject selfBean = dataArray.getJSONObject(0);
                                        if (selfBean != null && selfBean.size() > 0) {
                                            FamilyMemberBean.MemberBean bean = JSON.parseObject(selfBean.toJSONString(), FamilyMemberBean.MemberBean.class);
                                            members_list.add(bean);
                                        }
                                    }
                                    if (dataArray.size() > 1) {
                                        JSONArray authBean = dataArray.getJSONArray(1);
                                        if (authBean != null && authBean.size() > 0) {
                                            List<FamilyMemberBean.MemberBean> list = JSON.parseArray(authBean.toJSONString(), FamilyMemberBean.MemberBean.class);
                                            for (FamilyMemberBean.MemberBean bean : list) {
                                                members_list.add(bean);
                                            }
                                        }
                                    }

                                }
                            }
                            health_member_tab.removeAllTabs();
                            for (FamilyMemberBean.MemberBean bean : members_list) {
                                View view = getLayoutInflater().inflate(R.layout.lmc_custom_tab_item, health_member_tab, false);
                                ((TextView) view.findViewById(R.id.custom_tab_text)).setText(bean.getNiname());
                                TabLayout.Tab tab = health_member_tab.newTab().setCustomView(view);
                                health_member_tab.addTab(tab);
                            }
                            member_tv.setText(members_list.size() + "个家庭成员");
                            if (members_list.size() >= 5) {
                                iv_show_members.setVisibility(View.VISIBLE);
                            } else {
                                iv_show_members.setVisibility(View.GONE);
                            }

                        } catch (Exception e) {
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                    }
                });
            }
        }, 1000);
    }


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        Log.e("--------", "选择的下标位置：" + position);
        Get(members_list.get(position));
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_show_members) {
            if (members_list != null) {
                MembersActivity.start(getContext(), members_list);
            }
        } else if (v.getId() == R.id.edit_tv) {
            //编辑/完成
            if (adapter.getIsDrag() == 0) {
                //开始编辑（可以拖动listView)
                adapter.setIsDrag(1);
                listView.setToh(true);
                edit_tv.setText("完成");
            } else {
                adapter.setIsDrag(0);
                //提成完成
                listView.setToh(false);
                edit_tv.setText("编辑");
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * listView拖动排序
     *
     * @param from 开始的position
     * @param to   拖拽到的position
     */
    @Override
    public void onChange(int from, int to) {
        Health.DataBean.ResultBean art = list.get(from);
        //这里的处理需要注意下
        if (from < to) {
            for (int i = from; i < to; i++) {
                Collections.swap(list, i, i + 1);
            }
        } else if (from > to) {
            for (int i = from; i > to; i--) {
                Collections.swap(list, i, i - 1);
            }
        }
        list.set(to, art);
        adapter.notifyDataSetChanged();
        //完成排序（保存排序）
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Health.DataBean.ResultBean resultBean = list.get(position);
        if (resultBean.getName().equals("每日健康报告")) {
            //每日健康报告
            if (health != null && health.getData() != null && health.getData().getResult() != null && health.getData().getResult().size() > 0) {
                HealthReportActivity.start(getContext(), health);
            } else {
                ToastUtil.showTextToast(getContext(), "暂无数据");
            }

        } else {
            //其它的数据
            HeartRateActivity.start(getContext(), resultBean);
        }
    }

    /**
     * 切换人员后
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(FamilyMemberBean.MemberBean bean) {
        Get(bean);
    }


    /**
     * 切换机器人后
     *
     * @param busBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(EventBusBean busBean) {
        if (busBean.getId() == Constant.EventBusId.SWITCH_DEVICE_ID) {
            getMembers();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
